package cn.server;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Iterator;

import cn.util.Constant;

public class Listenner extends Thread {
	private static final int BLOCK = 1024;
	private SocketChannel channel = null;
	private ByteBuffer clientBuffer = ByteBuffer.allocate(Listenner.BLOCK);
	private boolean start = true;
	private Charset charset = Charset.forName("utf-8");
	private CharsetDecoder decoder = charset.newDecoder();

	public void run() {
		try {
			while (start) {
				DAServerSocketChannel.selector.select();
				Iterator<SelectionKey> iter = DAServerSocketChannel.selector
						.selectedKeys().iterator();
				while (iter.hasNext()) {
					SelectionKey key = (SelectionKey) iter.next();
					iter.remove();
					process(key);
				}
				Thread.sleep(500);
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (DAServerSocketChannel.selector != null)
					DAServerSocketChannel.selector.close();
				if (DAServerSocketChannel.userHash != null)
					DAServerSocketChannel.userHash.clear();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
	}

	protected void process(SelectionKey key) throws IOException {
		if (key.isReadable()) {
			this.channel = (SocketChannel) key.channel();
			int count = this.channel.read(clientBuffer);
			clientBuffer.flip();
			if (count > 0) {
				String content = decoder.decode(clientBuffer).toString();
				clientBuffer.clear();
				if (content.substring(0, Constant.CMD_LENGTH).equals("0001")) {
					regist(content, channel);
				} else {
					DAServerSocketChannel.msgList.addLast(content);
				}
			} else {
				channel.close();
			}
		}
	}

	public void stopListenner() {
		this.start = false;
	}

	public void startListenner() {
		this.start();
	}

	private void regist(String msg, SocketChannel socket) {
		String key = msg
				.substring(Constant.CMD_LENGTH, Constant.USER_ID_LENGTH);
		DAServerSocketChannel.userHash.put(key, socket);
	}
}